package JUC.printWhen5;


import java.io.IOException;
import java.util.ArrayList;

/**
 * @className: MyArrayList
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/9/4 11:35
 */
public class SyncArrayList {
    private ArrayList<Integer> list = new ArrayList<>();
    public void add(Integer i){
       list.add(i);
    }

    public int size(){
        return list.size();
    }

    public static void main(String[] args) {
        SyncArrayList array = new SyncArrayList();
        Object lock = new Object();
        new Thread(()->{
            synchronized (lock){
                if(array.size() != 4){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("size is 4");
                    lock.notify();
                }
                System.out.println("A end");
            }
        }).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
           synchronized (lock){
               for(int i = 0 ; i < 10 ; i++){
                   array.add(i);
                   if(i == 4){
                        lock.notify();
                       try {
                           lock.wait();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                   System.out.println("add " + i);
               }
               System.out.println("B end");
           }
        }).start();
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
